package com.example.im.http

import com.example.im.utils.LogUtils
import com.google.gson.Gson
import com.example.im.common.Constants
import okhttp3.*
import okio.Buffer
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory

import java.util.Locale
import java.util.concurrent.TimeUnit

/**
 * Created by Administrator on 2019/5/14.
 */
object RetrofitManager {

    private var mRetrofit: Retrofit? = null

    fun retrofit(): Retrofit {

        if (mRetrofit == null) {
            val builder = OkHttpClient.Builder()
                .writeTimeout(30.toLong(), TimeUnit.SECONDS)
                .readTimeout(30.toLong(), TimeUnit.SECONDS)
                .connectTimeout(30.toLong(), TimeUnit.SECONDS)
                .addInterceptor(LoggingInterceptor())

            mRetrofit = Retrofit.Builder()
                .baseUrl(Constants.HTTP_URL_INTRA_NET)
                .addConverterFactory(LenientGsonConverterFactory.create(Gson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build()
        }

        return mRetrofit!!
    }

    /**
     * Log拦截
     */
    internal class LoggingInterceptor : Interceptor {

        private val mediaType: MediaType = MediaType.parse("application/octet-stream")!!

        override fun intercept(chain: Interceptor.Chain): Response {

            //发送时截取数据
            val request = chain.request()
            val t1 = System.nanoTime()
            val body = request.body()
            val buffer = Buffer()
            body?.writeTo(buffer)
            LogUtils.d(
                String.format(
                    Locale.CHINA, ("发送请求:%s%n请求JSON:%s"),
                    request.url(),
                    buffer.readUtf8()
                )
            )
            //接收时截取数据
            val response = chain.proceed(request)
            val t2 = System.nanoTime()
            val responseBody = response.peekBody((1024 * 1024).toLong())
            LogUtils.d(
                String.format(
                    Locale.CHINA, ("接收响应:%s%n请求时间:%.1fms%n报文信息:%s返回JSON:%s"),
                    response.request().url(),
                    (t2 - t1) / 1e6,
                    response.headers(),
                    if (responseBody.contentType() == mediaType)
                        "This is the file download" else responseBody.string()
                )
            )
            return response
        }

    }

}
